package com.unicdata.ai.demo_2af.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.unicdata.ai.demo_2af.annotation.Log;
import com.unicdata.ai.demo_2af.common.entity.Permission;
import com.unicdata.ai.demo_2af.common.exception.BusinessException;
import com.unicdata.ai.demo_2af.common.result.Result;
import com.unicdata.ai.demo_2af.service.PermissionService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * 权限控制器
 *
 * @author lhn
 * @date 2025/06/25 17:07
 * @since 1.0.0
 **/
@RestController
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    /**
     * 权限列表
     */
    @GetMapping("/list")
    @RequiresPermissions("permission:view")
    @Log("查询权限列表")
    public Result<IPage <Permission>> list(@RequestParam(defaultValue = "1") Integer current,
                                           @RequestParam(defaultValue = "10") Integer size,
                                           @RequestParam(required = false) String permissionName) {
        Page<Permission> page = new Page <>(current, size);
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper <>();

        // 按权限名称模糊查询
        if (StringUtils.isNotBlank(permissionName)) {
            queryWrapper.like(Permission::getPermissionName, permissionName);
        }

        IPage<Permission> permissionPage = permissionService.page(page, queryWrapper);
        return Result.success(permissionPage);
    }

    /**
     * 获取所有权限
     */
    @GetMapping("/all")
    @RequiresPermissions("permission:view")
    public Result<List<Permission>> getAllPermissions() {
        List <Permission> permissions = permissionService.list();
        return Result.success(permissions);
    }

    /**
     * 获取权限详情
     */
    @GetMapping("/{permissionId}")
    @RequiresPermissions("permission:view")
    public Result<Permission> getPermission(@PathVariable Long permissionId) {
        if (permissionId == null) {
            throw new BusinessException("权限ID不能为空");
        }

        Permission permission = permissionService.getById(permissionId);
        if (permission == null) {
            return Result.error("权限不存在");
        }

        return Result.success(permission);
    }

    /**
     * 新增权限
     */
    @PostMapping
    @RequiresPermissions("permission:add")
    @Log("新增权限")
    public Result<Void> add(@RequestBody @Valid Permission permission) {
        if (StringUtils.isBlank(permission.getPermissionName())) {
            throw new BusinessException("权限名称不能为空");
        }
        if (StringUtils.isBlank(permission.getPermissionCode())) {
            throw new BusinessException("权限编码不能为空");
        }

        // 检查权限编码是否已存在
        Permission existPermission = permissionService.getPermissionByCode(permission.getPermissionCode());
        if (existPermission != null) {
            return Result.error("权限编码已存在");
        }

        permission.setCreateTime(new Date());
        permission.setUpdateTime(new Date());
        boolean success = permissionService.save(permission);

        if (success) {
            return Result.success(null, "权限添加成功");
        } else {
            return Result.error("权限添加失败");
        }
    }

    /**
     * 更新权限
     */
    @PutMapping
    @RequiresPermissions("permission:edit")
    @Log("更新权限")
    public Result<Void> update(@RequestBody @Valid Permission permission) {
        if (permission.getId() == null) {
            throw new BusinessException("权限ID不能为空");
        }
        if (StringUtils.isBlank(permission.getPermissionName())) {
            throw new BusinessException("权限名称不能为空");
        }

        // 检查权限是否存在
        Permission existPermission = permissionService.getById(permission.getId());
        if (existPermission == null) {
            return Result.error("权限不存在");
        }

        // 不允许修改权限编码
        permission.setPermissionCode(existPermission.getPermissionCode());
        permission.setUpdateTime(new Date());
        boolean success = permissionService.updateById(permission);

        if (success) {
            return Result.success(null, "权限更新成功");
        } else {
            return Result.error("权限更新失败");
        }
    }

    /**
     * 删除权限
     */
    @DeleteMapping("/{permissionId}")
    @RequiresPermissions("permission:delete")
    @Log("删除权限")
    public Result<Void> delete(@PathVariable Long permissionId) {
        if (permissionId == null) {
            throw new BusinessException("权限ID不能为空");
        }

        Permission permission = permissionService.getById(permissionId);
        if (permission == null) {
            return Result.error("权限不存在");
        }

        boolean success = permissionService.removeById(permissionId);

        if (success) {
            return Result.success(null, "权限删除成功");
        } else {
            return Result.error("权限删除失败");
        }
    }

}